import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'

import styles from './index.module.scss'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { login, getCode } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router'
import { AxiosError } from 'axios'
import { useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
import useCountDown from '@/hooks/useCountDown'
// import { useSelector } from 'react-redux'
// import { RootState } from '@/types/store'

const Login = () => {
  // const state = useSelector((state: RootState) => state.login)
  // 是否可以发验证码
  const location = useLocation<{from: string}>()
  const [sendable, setSendable] = useState(true)
  const { start, count } = useCountDown(60, () => { setSendable(true) })
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const history = useHistory()

  const onFinish = async (values: LoginForm) => {
    try {
      // 发请求-登录
      await dispatch(login(values))

      Toast.show({
        content: '登录成功'
      })
      // 页面跳转，如何从 state中取值？
      const pathname = location.state?.from
      history.push(pathname || '/home')
    } catch (e) {
      console.dir(e)
      // 类型 断言
      // messsage:我们确定后端会给一个message来说明错误原因
      const error = e as AxiosError<{ message: string }>

      let content = '错误'
      if (error.response) {
        content = error.response.data.message
      }
      Toast.show({
        icon: 'fail',
        content: content
      })
    }
  }
  const refInput = useRef<InputRef>(null)
  // 发验证码
  const onSend = async () => {
    // 1. 验证表单元素-手机号格式
    if (form.getFieldError('mobile').length > 0) {
      // 让 手机号所在的文本框自动获取焦点
      refInput.current!.focus()
      return
    }
    // 2. 获取表单元素的值
    const mobile = form.getFieldValue('mobile')

    // 调用接口向mobile发验证码
    try {
      await dispatch(getCode(mobile))
      Toast.show({ content: '短信已发送' })

      // 启动倒计时
      start()
      // 不可发送
      setSendable(false)
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({ content: error.response?.data.message })
    }
  }
  return (
    <div className={styles.root}>
      <NavBar />

      <div className="login-form">
        <h2 className="title">账号登录-{count}</h2>

        <Form
          form={form}
          initialValues={{ mobile: '13611111112', code: '246810' }}
          onFinish={onFinish}>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1\d{10}$/, message: '手机号格式不对' }
            ]}
            className="login-item">
            <Input placeholder="请输入手机号" ref={refInput} />
          </Form.Item>

          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra" onClick={sendable ? onSend : undefined}>
                {sendable ? '发送验证码' : `${count}秒之后再试`}
              </span>
            }>
            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '验证码格式不对' }
              ]}
              className="login-item">
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
